import { message, notification } from 'antd';
import { sleep } from '@/utils/utils';

export const request = {
    timeout: 5000,
    // other axios options you want
    errorConfig: {
      errorHandler(response: any) {
        notification.error({
          message: response?.message || '您的网络环境异常,请稍后再试',
        });
        console.log(response, '错误捕获');
      },
      errorThrower() {},
    },
    requestInterceptors: [
      // 直接写一个 function，作为拦截器
      (url: any, options: any) => {
        // console.log(url, options, localStorage.getItem);
        options.headers.Authorization = localStorage.getItem('auth-token');
        // do something
        return { url, options };
      },
    ],
    responseInterceptors: [
      [
        async (response: any) => {
          const { status } = response;
          if (status === 200) {
            if (response.data?.code === 401) {
              notification.error({
                message: '您的网络环境异常，请重新登录',
              });
              localStorage.removeItem('auth-token');
              await sleep(1500);
              window.location.href = '/login';
            } else if (response.data?.code === 403) {
              notification.error({
                message: '您没有权限访问该资源',
              });
            } else if (response.data?.code >= 500) {
              message.error(response?.data?.msg || '服务器内部错误');
            }
          } else if (status >= 500) {
            message.error('您的网络环境异常');
          } else {
            message.error('请求错误');
          }
          console.log(response, 'response');
          return response;
        },
      ],
    ],
  };